﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace TransCend.Util
{
    /// <summary>
    /// 字符串处理
    /// </summary>
    public class StringUtils
    {
        /// <summary>
        ///     BASE64解码（使用UTF-8编码格式）
        /// </summary>
        /// <param name="encodedString">BASE64编码后的字符串</param>
        /// <returns></returns>
        public static string FromBase64String(string encodedString)
        {
            return FromBase64String(encodedString, Encoding.UTF8);
        }

        /// <summary>
        ///     BASE64解码（使用指定的编码格式）
        /// </summary>
        /// <param name="encodedString">BASE64编码后的字符串</param>
        /// <param name="encoding">编码格式</param>
        /// <returns></returns>
        public static string FromBase64String(string encodedString, Encoding encoding)
        {
            byte[] b = Convert.FromBase64String(encodedString);
            string decodedString = encoding.GetString(b);
            return decodedString;
        }

        /// <summary>
        ///     BASE64编码（使用UTF-8格式）
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ToBase64String(string value)
        {
            return ToBase64String(value, Encoding.UTF8);
        }

        /// <summary>
        ///     BASE64编码（使用指定编码格式）
        /// </summary>
        /// <param name="value"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string ToBase64String(string value, Encoding encoding)
        {
            byte[] b = encoding.GetBytes(value);
            return Convert.ToBase64String(b);
        }

        /// <summary>
        /// 判断字符串是否是null或者string.Empty或者只包含空格
        /// 为了兼容.net framework4.0，特增加此方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNullOrWhiteSpace(string value)
        {
            if (string.IsNullOrEmpty(value)) return true;
            if (string.IsNullOrEmpty(value.Trim())) return true;
            return false;
        }

        public static string HtmlEncode(string input)
        {
            return HttpUtility.HtmlEncode(input);
        }

        public static string HtmlDecode(string input)
        {
            return HttpUtility.HtmlDecode(input);
        }

        /// <summary>
        /// 截取字符串,中文占2个字节
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="len">截取的长度</param>
        /// <param name="hasOmit">是否有省略符</param>
        /// <param name="omitValue">省略符</param>
        /// <returns>截取字符串</returns>
        public static string GetCnString(string str, int length, bool hasOmit, string omitValue)
        {
            StringBuilder sb = new StringBuilder();
            int len = 0;
            foreach (char c in str)
            {
                if ((int)c > 256)
                    len += 2;
                else
                    len++;
                if (len < length)
                    sb.Append(c);
                else
                {
                    if (hasOmit)
                        sb.Append(omitValue);
                    else
                        sb.Append(c);
                    break;
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 中文两个
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int StrLength(string str)
        {
            int len = 0;
            for (int i = 0; i < str.Length; i++)
            {
                byte[] byte_len = System.Text.Encoding.Default.GetBytes(str.Substring(i, 1));
                if (byte_len.Length > 1)
                    len += 2;
                else
                    len += 1;
            }
            return len;
        }

        /// <summary>
        /// SQL 字符串拼接前字符串转换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReplaceSecStr(string str)
        {
            string returnvalue = "";
            if (null != str)
            {
                str = str.Replace("'", "''");
                str = str.Replace("[", "");
                str = str.Replace("<", "");
                returnvalue = str.Trim();
            }
            return returnvalue;
        }

        private static Regex regex = new Regex("<[^<^>]+>");
        private static Regex regexHand = new Regex(@"<script[\s\S]+</script*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        private static Regex regexHand2 = new Regex("&\\w+;");
        /// <summary>
        /// 过滤HTML元素
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string FilterHtml(string html)
        {
            html = regex.Replace(regexHand.Replace(html, ""), "");
            html = regexHand2.Replace(html, "");
            html = html.Replace(" ", "");
            html = html.Replace("\r\n\r\n", "").Trim();

            return html;
        }

        public static string XssFilter(string value) {
            StringBuilder result = new StringBuilder(value.Length);
            for (int i = 0; i < value.Length; ++i)
            {
                string v = value.Substring(i, 1);
			    switch (v) {
			    case "<":
				    result.Append("&lt;");
				    break;
			    case ">":
                    result.Append("&gt;");
				    break;
                /*case """:
                    result.Append("&quot;");
                    break;
                case "\"":
                    result.Append("&#39;");
                    break; */
                case "%":
                    result.Append("&#37;");
				    break;
                /*case ";":
                    result.Append("&#59;");
                    break;
                case "(":
                    result.Append("&#40;");
                    break;
                case ")":
                    result.Append("&#41;");
                    break; */
                case "&":
                    result.Append("&amp;");
				    break;
			    case "+":
                    result.Append("&#43;");
				    break;
			    default:
                    result.Append(v);
				    break;
			    }
		    }
            return result.ToString();
	    }

        static Regex SQL_FIELD_PATTERN = new Regex("^[0-9A-Za-z_\\,]{0,100}$");
        /// <summary>
        /// 是否安全SQL字段
        /// </summary>
        /// <param name="field"></param>
        public static void AssertSQLField(string field)
        {
            if (!string.IsNullOrEmpty(field))
            {
                MatchCollection matcher = SQL_FIELD_PATTERN.Matches(field);
                if (matcher.Count <= 0)
                {
                    throw Exceptions.SystemException.GetSystemException(Exceptions.ExceptionErrorCode.ERROR, null);
                }
            }
        }

        /// <summary>
        /// 
        /// 替换的旧值中有特殊符号，替换将会失败，解决办法 例如特殊符号是“(”：  
        /// 要在调用本方法前加oldValue=oldValue.Replace("(","//(");
        /// </summary>
        /// <param name="input"></param>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        /// <returns></returns>
        public static string ReplaceFirst(string input, string oldValue, string newValue)
        {
            Regex regEx = new Regex(oldValue, RegexOptions.Multiline);
            return regEx.Replace(input, newValue == null ? "" : newValue, 1);

        } 
    }
}
